<template>
    <el-dialog :visible="visible" @close="cancel" width="80%">
        <div style="height: calc(100vh - 200px)">
          <el-row :gutter="20">
            <!--分类数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                <el-input
                    v-model="itemTypeName"
                    placeholder="请输入分类名称"
                    clearable
                    size="small"
                    prefix-icon="el-icon-search"
                    style="margin-bottom: 20px"
                />
                </div>
                <div style="height: calc(100vh - 300px);overflow: auto;">
                <el-tree
                    :data="itemTypeOptions"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                    :default-expanded-keys="treeData"
                    node-key="id"
                    ref="tree"
                    @node-click="handleNodeClick"
                />
                </div>
            </el-col>
            <!--物料数据-->
            <el-col :span="20" :xs="24">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="物料编码" prop="itemCode">
                    <el-input
                    v-model="queryParams.itemCode"
                    placeholder="请输入物料编码"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="物料名称" prop="itemName">
                    <el-input
                    v-model="queryParams.itemName"
                    placeholder="请输入物料名称"
                    clearable
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
                </el-form>

                <el-table v-loading="loading" :data="itemList" ref="tableRef"
                height="calc(100vh - 300px)"
                @selection-change="handleSelectionChange"  row-key="itemCode">
                    <el-table-column type="selection"  width="50" align="center" :reserve-selection="true"/>
                    <el-table-column type="index" label="序号" align="center" width="50" />
                    <el-table-column label="物料编码" width = "120" align="center" key="itemCode" prop="itemCode" v-if="columns[0].visible" >
                        <template slot-scope="scope">
                            <el-button
                            size="mini"
                            type="text"
                            @click="handleView(scope.row)"
                            >{{scope.row.itemCode}}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="物料名称"  align="center" key="itemName" prop="itemName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
                    <el-table-column label="规格型号" width="210" align="center" key="specification" prop="specification" v-if="columns[2].visible" :show-overflow-tooltip="true" />
                    <el-table-column label="单位" align="center"  prop="unitOfMeasure" v-if="columns[3].visible" :show-overflow-tooltip="true" >
                    </el-table-column>
                    <el-table-column label="所属分类" align="center" key="itemTypeName" prop="categoryName" v-if="columns[5].visible" width="120" />
                    <el-table-column label="是否启用" align="center" key="enableFlag" v-if="columns[6].visible">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.enableFlag"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="标准工时"  align="center" key="perUnitStandHour" prop="perUnitStandHour"  />
                    <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[8].visible" width="160">
                        <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                
                </el-table>

                <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
                />
            </el-col>
            </el-row>
           
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="confirmSelect">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
</template>
<script>
    import { mdItemList, getMdItem, delMdItem, addMdItem, updateMdItem,synchronousData ,attachmentDownLoad, attachmentPreview } from "@/api/mes/md/mdItem";

import { listAllUnitmeasure} from "@/api/mes/md/unitmeasure";
import {genCode} from "@/api/mes/md/rule"
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/mes/md/itemtype";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { onMounted } from "vue-demi";
export default {
  name: "SelectMaterialDialog",
  dicts: ['sys_yes_no','mes_item_product'],
  components: { Treeselect },
  data() {
    return {
      preselectedItemList: [],
      selectedItemList: [],
      // 遮罩层
      loading: true,
      visible:false,        
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料产品表格数据
      itemList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      itemTypeOptions: undefined,
      // 是否显示弹出层
      open: false,
      //弹框的操作类型 view add edit
      optType: undefined,
      // 部门名称
      itemTypeName: undefined,
      //自动生成物料编码标识
      autoGenFlag: false,
      // 日期范围
      dateRange: [],
      //单位列表
      measureOptions: [],
      treeData: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined,
        itemName: undefined,
        itemTypeId: null
      },
      // 列信息
      columns: [
        { key: 0, label: `物料/产品编码`, visible: true },
        { key: 1, label: `物料/产品名称`, visible: true },
        { key: 2, label: `规格型号`, visible: true },
        { key: 3, label: `单位`, visible: true },
        { key: 4, label: `物料/产品`, visible: true },
        { key: 5, label: `物料分类`, visible: true },
        { key: 6, label: `是否启用`, visible: true },
        { key: 7, label: `是否设置安全库存`, visible: true },
        { key: 8, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "物料/产品编码不能为空", trigger: "blur" },
          { max: 64, message: '物料/产品编码长度必须小于64个字符', trigger: 'blur' }
        ],
        itemName: [
          { required: true, message: "物料/产品名称不能为空", trigger: "blur" }
        ],
        unitOfMeasure: [
          { required: true, message: "单位不能为空",trigger: "blur"}
        ],
        itemTypeId: [
          { required: true, message: "物料分类不能为空", trigger: "blur" },
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选分类树
    itemTypeName(val) {
      this.$refs.tree.filter(val);
    },
    visible(val){
      if(val){
        this.getList();
        this.getTreeselect();
        this.getUnits();
      }
    }
  },
  onMounted() {
    this.getList();
    this.getTreeselect();
    this.getUnits();
  },
  methods: {
    init(rows){
      if(rows.length > 0){
        this.preselectedItemList = rows;
      }else{
        this.preselectedItemList = [];
      }
      this.visible = true;
    },
    toggleSelectedRows(rows){
      if(rows.length > 0){
        let selectedRows = this.itemList.filter(item=>rows.filter(subItem=>subItem.itemCode === item.itemCode).length > 0)
        selectedRows.forEach(row=>
        this.$refs.tableRef.toggleRowSelection(row,true)
        )
      }
    },
    /** 查询物料编码列表 */
    getList() {
      this.loading = true;
      mdItemList(this.queryParams).then(response => {
        let arr = response.rows || []
          this.itemList = arr.map(item => {
            if((typeof item.ftbibAttachment) === 'string'){
              item.newFtbibAttachment = item.ftbibAttachment.trim();
            }else {
              item.newFtbibAttachment = item.ftbibAttachment
            }
            return item
          })
          this.total = response.total;
          this.loading = false;
          this.$nextTick(() => {
            this.toggleSelectedRows(this.preselectedItemList)
          })
        }
      );
    },
    getUnits(){
      listAllUnitmeasure().then(response =>{
        this.measureOptions = response.data;
      });
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.treeData.push(response.data[0].id)
        this.treeData.push(response.data[1].id)
        this.itemTypeOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.itemTypeId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.visible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itemId: undefined,
        itemTypeId: undefined,
        itemCode: undefined,
        itemName: undefined,
        specification: undefined,
        unitOfMeasrue: undefined,
        // enableFlag: undefined,
        itemOrProduct: undefined,
        enableFlag: 'Y',
        safeStockFlag: 'N',
        minStock: 0,
        maxStock: 0,
        optType: undefined,
        remark: undefined,
        jdyItemId:undefined
      };
      this.resetForm("form");
      this.selectedItemList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    confirmSelect(){
      this.$emit('onSelection',this.selectedItemList);
      this.cancel();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedItemList = selection;
    },
  }
};
</script>
<style>
.head-container{
  height: 100%;
  overflow-y: scroll;
}
</style>